from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from utils.user import LoginRequiredJSONMixin
from apps.orders.models import OrderInfo
from alipay import AliPay
from django.conf import settings

class AlipayURLView(LoginRequiredJSONMixin,View):
    def get(self,request,order_id):
        # 1. 获取订单id
        # 2. 根据订单id查询订单信息
        order = OrderInfo.objects.get(order_id=order_id,
                                      status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'],
                                      user = request.user)
        # 3. 生成支付宝支付链接
        private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=private_key_string,
            alipay_public_key_string=public_key_string)

        # 生成支付的string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,                      # 支付订单的id
            total_amount=str(order.total_amount),       # 支付总金额,修改为str类型
            subject='美多商城支付',                       # 主题
            return_url=settings.ALIPAY_RETURN_URL,           # 支付成功之后的回调地址
            notify_url=settings.ALIPAY_RETURN_URL  # 可选, 不填则使用默认notify url
        )

        # 支付的url
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return JsonResponse({'code':0,'alipay_url':alipay_url})

class PaymentStatusView(View):
    def put(self,request):
        # 1. 接收参数 把数据转换为字典
        data = request.GET.dict()
        # 2. 提取参数
        # 3. 验证参数 文档有验证方法
        signature = data.pop("sign")

        private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=private_key_string,
            alipay_public_key_string=public_key_string)
        success = alipay.verify(data, signature)
        if success:
            from apps.payment.models import Payment
            # 4. 保存支付宝订单id和美多订单id
            # 美多订单id
            order_id = data.get('out_trade_no')
            # 支付宝订单id
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
            # 5. 修改订单状态
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            # 6. 返回响应
            return JsonResponse({'code':0,'trade_id':trade_id})
        return JsonResponse({'code':400,'errmsg':'稍后查询支付信息'})